package com.googlecode.garbagecan.cxfstudy.jaxrs;

import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class MyClient {

	public static void main(String[] args) throws Exception {
		long start = System.currentTimeMillis();
		testHttpClientForObject("http://localhost:9000/ws/jaxrs/customer/1/info");
		testHttpClientForObject("http://localhost:9000/ws/jaxrs/customer/search?name=abc");
		testHttpClientForString("http://localhost:9000/ws/jaxrs/customer/1/name");
		testJAXRSClient();
		long stop = System.currentTimeMillis();
		System.out.println("\n--------------------");
		System.out.println("Time: " + (stop - start));
	}
	
	private static void testHttpClientForObject(String url) throws Exception {
		System.out.println("\n---------- testHttpClientForObject ----------");
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = httpclient.execute(httpget, responseHandler);
		System.out.println("json: " + responseBody);
		
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").create();
		JsonParser parser = new JsonParser();
		JsonElement jsonEle = parser.parse(responseBody);
		jsonEle = jsonEle.getAsJsonObject().get("Customer");
		Customer customer = gson.fromJson(jsonEle, Customer.class);
		System.out.println("customer: " + customer);
	}
	
	private static void testHttpClientForString(String url) throws Exception {
		System.out.println("\n---------- testHttpClientForString ----------");
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = httpclient.execute(httpget, responseHandler);
		System.out.println("result: " + responseBody);
	}
	
	private static void testJAXRSClient() throws Exception {
		System.out.println("\n---------- testJAXRSClient ----------");
		CustomerService customerService = JAXRSClientFactory.create("http://localhost:9000/ws/jaxrs", CustomerService.class);
		System.out.println(customerService.findCustomerById("1"));
		System.out.println(customerService.getCustomerNameById("1"));
		System.out.println(customerService.findCustomerByName("kongxx"));
	}
}
